package com.hucsmn.stumansys.servlet.admin;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.hucsmn.stumansys.entity.Admin;
import com.hucsmn.stumansys.service.AdminService;
import com.hucsmn.stumansys.utils.ConvertUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 管理员账户名存在性检测 API。
 *
 * 接收 HTTP 参数
 *      name    管理员用户名。
 *
 * 响应 JSON 数据
 *      code    状态码。0 表示成功。
 *      msg     操作出错原因。
 *      exists  账户名是否存在。true 存在，false 不存在。
 *
 * @author hucsmn
 */
@WebServlet("/api/admin/exists")
public class AdminExistsServlet extends HttpServlet {
    private final AdminService adminService = AdminService.getInstance();
    private final Gson gson = new GsonBuilder().create();

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=UTF-8");

        String name = ConvertUtils.normalizeText(request.getParameter("name"));
        JsonObject result = new JsonObject();
        if (adminService.exists(name)) {
            result.addProperty("code", 0);
            result.addProperty("msg", "");
            result.addProperty("exists", true);
        } else {
            result.addProperty("code", 0);
            result.addProperty("msg", "");
            result.addProperty("exists", false);
        }

        PrintWriter out = response.getWriter();
        out.write(gson.toJson(result));
        out.flush();
        out.close();
    }
}
